/* eslint-disable prefer-const */
/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable no-else-return */
/* eslint-disable no-console */
// import { PlusOutlined } from '@ant-design/icons';
import { getGreeProductsFromMysql, getsubinfo, saveAndupdataProductSub } from '@/services/ant-design-pro/api';
import { PageContainer } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Badge, message } from 'antd';
import moment from 'moment';
import React, { useRef, useState } from 'react';
import { FormattedMessage, history, useModel} from 'umi';
// import { useRequest } from '@umijs/hooks';
import type { FormValueType } from './components/SubForm';
import SubForm from './components/SubForm';


/**
 * @en-US Update node
 * @zh-CN 更新节点
 *
 * @param fields
 */
const handleSaveAndUpdate = async (fields: FormValueType) => {
  const hide = message.loading('Configuring');
  console.log("FormValueType:", fields)
  try {
    // await getGreeProductStates("123456789","46006304228299")
    const resp = await saveAndupdataProductSub(fields);
    console.log("resp:", resp);
    hide();

    message.success('订阅成功');
    return true;
  } catch (error) {
    hide();
    message.error('订阅失败!');
    return false;
  }
};

/* const devlist = await getGreeProductsFromDg(params1)
console.log(devlist.data) */

// console.log(devlist2)
/* const devstates = await getGreeProductStates("123456789","46006304228299")
console.log(devstates.data)  */

/* getGreeProductStates("123456789", "46006304228299").then(res => {
  console.log(res)
}) */

/* getGreezhucheProductstates().then(res =>{
console.log(res)
}) */

const DevList: React.FC = () => {
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  // const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const { initialState, setInitialState } = useModel('@@initialState');
  const [SubModalVisible, handleSubModalVisible] = useState<boolean>(false);

  // const [showDetail, setShowDetail] = useState<boolean>(false);

  const actionRef = useRef<ActionType>();
  // const formRef = useRef<FormInstance>();

  // const [currentRow, setCurrentRow] = useState<API.GreeProductItem>();
  // const [selectedRowsState, setSelectedRows] = useState<API.GreeProductItem[]>([]);
  const [subFormVal, setSubFormVal] = useState<API.SubFormVal>();
  const [polling] = useState<number | undefined>(10000);  // 10S轮询一次
  // getGreeProductsFromMysql(params, { sorter, filter })
  /*
  params: {
    current?: number;
    pageSize?: number;
  },  */
  //  actionRef.current?.

/*   const products = useRequest(getGreeProductsFromMysql, {
    pollingInterval: 10000,
    pollingWhenHidden: false,
  }); */

  // console.log("products:", products);
  /*    int_timer.current = setInterval(async () => {
  
      // console.log("ddd",products.data);
      // products.refresh();
      if (actionRef.current) {
        actionRef.current.reload();
      }
  
    }, 10000);  */

  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
  // const intl = useIntl();

  const columns: ProColumns<API.GreeProductItem>[] = [
    {
      title: "类别",
      hideInSearch: true,
      // hideInForm: true,
      // sorter: true,
      dataIndex: 'devicetype',
      sorter: (a, b) => a.devicetype > b.devicetype ? 1 : -1,
      // tip: 'The rule name is the unique key',
      align: "center",

    },
    {
      title: "型号",
      // sorter: true, 
      dataIndex: 'devicemodel',
      valueType: 'textarea',
      sorter: (a, b) => a.devicemodel > b.devicemodel ? 1 : -1,
      align: "center",
    },
    {
      title: "条码",
      dataIndex: 'barcode',
      // sorter: true,
      sorter: (a, b) => a.barcode > b.barcode ? 1 : -1,
      // hideInForm: true,
      /*        renderText: (val: string) =>
               `${val}${intl.formatMessage({
                 id: 'pages.searchTable.tenThousand',
                 defaultMessage: ' 万 ',
               })}`, */
      align: "center",
    },
    {
      title: "标识",
      sorter: (a, b) => a.deviceimsi > b.deviceimsi ? 1 : -1,
      dataIndex: 'devlabel',
      valueType: 'textarea',
      align: "center",
    },
    {
      title: "在线",
      dataIndex: 'status',
      // hideInForm: true,
      hideInSearch: true,
      align: "center",
      render: (text: React.ReactNode, row, _: number) => {
        let offTime: number = 5+5;
        if (row.status?.controlsw.con) {
          offTime = 5;
        }
        // let updatetime = new Date(row.updatetime); 
        /*         let offlinetime = new Date(now.valueOf() - 60 * 1000 *10);// 当前时间加上1分钟*10
                console.log("offlinetime",offlinetime.valueOf());
                console.log("updatetime:",updatetime.valueOf())
                console.log("*-*",(now.valueOf()-updatetime.valueOf()-60 * 1000 * 10)); */
        const updatetime = new Date(row.status?.updatetime || "");
        const now = new Date();
        if ((now.valueOf() - updatetime.valueOf() < 60*1000*offTime)) {
          return (<Badge status="processing" text="在线" />)
        } else {
          return (<Badge status="default" text="离线" />)
        }
      },
    },
    {
      title: "状态",
      dataIndex: 'status',
      // sorter: true,
      hideInSearch: true,
      align: "center",
      render: (_, val) => {
        // let con = val.status?.controlsw.con ? "开机" : "关机";
        const a = val.status?.deverr ? "：" : "";
        let run_mode: string = "关机";
        if (val.status?.controlsw.con) {
          switch (val.status?.controls.cmode) {
            case 0:
              run_mode = "自动";
              break;
            case 1:
              run_mode = "制冷";
              break;
            case 2:
              run_mode = "除湿";
              break;
            case 3:
              run_mode = "送风";
              break;
            case 4:
              run_mode = "制热";
              break;
            default:
              run_mode = "开机";
              break;
          }
        }
        const status = run_mode + a + val.status?.errstr;
        return (<Badge status={val.status?.deverr ? "error" : "processing"} text={status} />);
        // eslint-disable-next-line no-lone-blocks
        {/* if (val.status.deverr) {
          return (<span> {val.status.errstr} </span>)
        } else {
          return (<span> {val.status.controlsw.con ? "开机" : "关机"} </span>)
        } 

      /*    render: (_, val) =>val.deverr?val.status.errstr:(val.status.controlsw.Con_off?"开机":"关机"), 
      */}
      }
    },
    /*     {
          title: "上线时间",
          sorter: true,
          dataIndex: 'createdtime',
          valueType: 'dateTime',
        }, */
    {
      title: "更新时间",
      // sorter: true,
      dataIndex: 'status',
      // hideInForm: true,
      // valueType: 'dateTime',
      hideInSearch: true,
      align: "center",
      sorter: (a, b) => a.status.updatetime > b.status.updatetime ? 1 : -1,
      render: (_, val) => {
        const updatatimestr = moment(val.status.updatetime).format('YYYY-MM-DD HH:mm:ss');
        return <span> {updatatimestr} </span>
      }
    },

    {
      title: <FormattedMessage id="pages.searchTable.titleOption" defaultMessage="操作" />,
      dataIndex: 'option',
      valueType: 'option',
      align: "center",
      render: (_, record) => [
        <a
          key="config"
          onClick={async () => {
            // handleSubModalVisible(true);
            // setCurrentRow(record);
            // 发起网络请求的参数,与 request 配合使用
            const subparams = {
              userid: initialState?.currentUser?.id,
              phone: initialState?.currentUser?.mobile,
              productid: record.id,

            };
            // 发起网络请求的参数,返回值会覆盖给 initialValues
            /*             let productsub = await getsubinfo(subparams)
                          .then(resp => {
                            console.log("subinfo:", resp)
                            return { ...resp.data }
                          }
                          );
                        setSubFormVal({
                          product: record,
                          productsub: productsub,
                        }); */
            getsubinfo(subparams)
              .then(resp => {
                console.log("subinfo:", resp);
                setSubFormVal({
                  product: record,
                  productsub: resp.data,
                })
                console.log("SubFormVal=", subFormVal);
                // 必须先异步取得数据才能打开弹窗，否则数据无法更新到from表的initialValues
                handleSubModalVisible(true);
              }
              );

          }
          }
        >
          <FormattedMessage id="pages.searchTable.subscribeAlert" defaultMessage="订阅警报" />
        </a >,
      ],
    },

  ];

  return (
    <PageContainer>
      <ProTable<API.GreeProductItem, API.PageParams>
        headerTitle="格力产品列表"
        actionRef={actionRef}
        // 10S轮询一次
        polling={polling || undefined}
        // formRef = {formRef}
        rowKey="id"
        options={{ reload: true }}
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          /*           <Button
                      type="primary"
                      key="primary"
                      onClick={() => {
                        // handleModalVisible(true);
                      }}
                    >
                      <PlusOutlined />新建
                    </Button>, */
        ]}

        /*       request={(params, sorter, filter) => {
                // 表单搜索项会从 params 传入，传递给后端接口。
                console.log(params, sorter, filter); */

        request={(params, sorter, filter) => getGreeProductsFromMysql(params, { sorter, filter })}
        // dataSource = {products.data}
        columns={columns}
        /*         rowSelection={{
                  onChange: (_, selectedRows) => {
                    setSelectedRows(selectedRows);
                    console.log(selectedRows);
                  },
                }} */
        pagination={{
          // pageSize:2,
          // current:1,
          defaultPageSize: 10,
        }}
        onRow={record => {
          return {
            // onClick: event => {console.log(record)}, // 点击行
            onDoubleClick: event => {
              // console.log(record);
              // 使用stata 参数传弟，state刷新后保存，使用共享变量，刷新后不保存
              setInitialState((s) => ({
                ...s,
                // device_select: record,
                device_id: record.id,
                device_imsi: record.deviceimsi
              }));
              history.push({
                pathname: '/devstates',
                // 使用stata 参数传弟，state刷新后保存
                state: {
                  // devselect: JSON.stringify(record),
                  device_imsi: record.deviceimsi,
                  device_id: record.id,
                },
              });
            },
            // onContextMenu: event => { console.log(record) },
            // onMouseEnter: event => {console.log("in")}, // 鼠标移入行
            // onMouseLeave: event => {console.log("out")},
          };
        }}
      />
      {/*       {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              <FormattedMessage id="pages.searchTable.chosen" defaultMessage="Chosen" />{' '}
              <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a>{' '}
              <FormattedMessage id="pages.searchTable.item" defaultMessage="项" />
              &nbsp;&nbsp;
              <span>
                <FormattedMessage
                  id="pages.searchTable.totalServiceCalls"
                  defaultMessage="Total number of service calls"
                />{' '}
                {selectedRowsState.reduce((pre, item) => pre, 0)}{' '}
                <FormattedMessage id="pages.searchTable.tenThousand" defaultMessage="万" />
              </span>
            </div>
          }
        >
          <Button
            onClick={async () => {
              // await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            <FormattedMessage
              id="pages.searchTable.batchDeletion"
              defaultMessage="Batch deletion"
            />
          </Button>
          <Button type="primary">
            <FormattedMessage
              id="pages.searchTable.batchApproval"
              defaultMessage="Batch approval"
            />
          </Button>
        </FooterToolbar>
      )} */}

      <SubForm
        onSubmit={async (values) => {
          // 补充保存信息
          const allvalues = {
            userid: initialState?.currentUser?.id,
            productid: subFormVal?.product?.id,
            ...values,
          };
          console.log("submit value:", allvalues)
          const success = await handleSaveAndUpdate(allvalues);
          if (success) {
            handleSubModalVisible(false);
            // setCurrentRow(undefined);
            setSubFormVal(undefined);
            /*             if (actionRef.current) {
                          actionRef.current.reload();
                        } */
          }
        }}
        onCancel={() => {
          handleSubModalVisible(false);
          // setCurrentRow(undefined);
          setSubFormVal(undefined);
        }}
        SubModalVisible={SubModalVisible}
        // values={currentRow || {}}
        values={subFormVal || {}}
      />
    </PageContainer>
  );
};

export default DevList;
